<script setup lang="ts">
let outerTimer: number
onMounted(() => {
  const box = document.getElementById('rainBox')
  let boxHeight = box?.clientHeight || 0
  let boxWidth = box?.clientWidth || 0
  // 页面大小发生变化时，改变盒子大小
  window.onresize = function () {
    boxHeight = box?.clientHeight || 0
    boxWidth = box?.clientWidth || 0
  }
  // 每隔一段时间,添加雨滴
  outerTimer = setInterval(() => {
    const rain = document.createElement('div')
    rain.classList.add('rain')
    rain.style.top = String(0)
    // 随机刷新雨点位置
    rain.style.left = Math.random() * boxWidth + 'px'
    // 随机雨点透明度
    rain.style.opacity = String(Math.random())
    box?.appendChild(rain)
    // 每隔一段时间,雨水下落
    let race = 1
    const timer = setInterval(() => {
      // 判断“雨滴”元素的top属性是否超出“盒子”元素的高度来决定是否停止动画
      if (parseInt(rain.style.top) > boxHeight) {
        clearInterval(timer)
        box?.removeChild(rain)
      }
      // 每次定时器执行时，“雨滴”元素的top值会逐渐增加，
      //并且增加的速率会随着时间的推移而逐渐加快
      race++
      rain.style.top = parseInt(rain.style.top) + race + 'px'
    }, 20)
  }, 50)
})
onUnmounted(() => {
  clearInterval(outerTimer)
})
</script>

<template>
  <teleport to="body">
    <div id="rainBox"></div>
    <div class="content"></div>
  </teleport>
</template>

<style scoped lang="scss">
.content {
  width: 100vw;
  height: 100vh;
  /* 图片链接 */
  /* background: url(https://w.wallhaven.cc/full/yx/wallhaven-yxe3jk.jpg) center center no-repeat; */
  background-size: 120%;
}
#rainBox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  /* 不阻挡其他元素事件触发 */
  pointer-events: none;
  z-index: 150;
}
</style>

<style lang="scss">
.rain {
  position: absolute;
  width: 2px;
  height: 50px;
  background: linear-gradient(rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.6));
}
</style>
